package com.googlecode.monitoring.builders;

import com.googlecode.monitoring.model.Person;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.HashSet;
import java.util.Set;

/**
 * Author: Sergiy Doroshenko
 * Date: Sep 20, 2010
 * Time: 3:21:15 PM
 */
public class DefaultPersonBuilder implements PersonBuilder {
    @Override
    public Person buildPerson(Node node) {
       if (node != null) {
			String fname = null, sname = null, email = null;
			if (node.getAttributes().getNamedItem("fname") != null) {
				fname =node.getAttributes().getNamedItem("fname").getNodeValue();
			}
			if (node.getAttributes().getNamedItem("sname") != null) {
				sname = node.getAttributes().getNamedItem("sname").getNodeValue();
			}
            if (node.getAttributes().getNamedItem("email") != null) {
                email = node.getAttributes().getNamedItem("email").getNodeValue();
            }

            return new Person(fname,sname,email);
        }
        return null;
    }

    @Override
    public Set<Person> buildPersons(NodeList personNodeList) {
        if (personNodeList != null && personNodeList.getLength() > 0) {
            Set<Person> plist = new HashSet<Person>(personNodeList.getLength());

            for (int i = 0; i < personNodeList.getLength(); i++) {
                plist.add(buildPerson(personNodeList.item(i)));
            }

            return plist;
        } else {
            return new HashSet<Person>();
        }
    }
}
